﻿using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Quartz;
using SchedulerManager.Entity;
using SchedulerManager;
using System.Reflection;

namespace ApiServer.Controllers.ServiceAPI
{
    /// <summary>
    /// 可视化调度QuartZ任务控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class QuartZJobController : ControllerBase
    {
        private readonly ILogger<QuartZJobController> _logger;
        private readonly SchedulerCenter _SchedulerCenter;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="schedulerCenter"></param>
        public QuartZJobController(ILogger<QuartZJobController> logger, SchedulerCenter schedulerCenter)
        {
            _logger = logger;
            this._SchedulerCenter = schedulerCenter;
        }

        /// <summary>
        /// 获取所有任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllJob")]
        public async Task<IActionResult> GetAllJob()
        {
            List<JobInfoEntity> list = await _SchedulerCenter.GetAllJobAsync();

            return new JsonResult(
                new ApiResultData<List<JobInfoEntity>>()
                {
                    Data = list,
                    Success = true,
                    Message = "获取所有任务"
                }
            );
        }

        /// <summary>
        /// 上传实现Job的程序集
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [Route("UploadDllFile")]
        [HttpPost]
        public JsonResult UploadDllFile([FromForm] IFormFile file)
        {
            string suffix = string.Empty;
            #region 获取文件后缀
            string filename = file.FileName.Trim();
            int index = filename.LastIndexOf(".");
            if (index > 0 && index < filename.Length - 1)
            {
                suffix = filename.Substring(index + 1);
            }
            #endregion
            if (!suffix.Equals("dll"))
            {
                return new JsonResult(
                    new ApiResultData<string>() { Success = false, Message = "格式错了" }
                );
            }
            #region 重新命名保存文件的名字
            string saveFilePath = $"{Directory.GetCurrentDirectory()}";
            if (Directory.Exists(saveFilePath) == false)
            {
                Directory.CreateDirectory(saveFilePath);
            }
            #endregion
            try
            {
                string allSaveFilePath = $"{saveFilePath}\\{filename}";
                using (var stream = System.IO.File.Create(allSaveFilePath))
                {
                    file.CopyToAsync(stream);
                }
                Assembly assembly = Assembly.LoadFrom(allSaveFilePath);
                Type? type = assembly
                    .GetTypes()
                    .FirstOrDefault(t => typeof(IJob).IsAssignableFrom(t));

                ApiResultData<object> result;
                if (type == null)
                {
                    result = new ApiResultData<object>()
                    {
                        Success = false,
                        Message = "job必须实现Ijob接口"
                    };
                }
                else
                {
                    result = new ApiResultData<object>()
                    {
                        Success = true,
                        Message = "文件上传成功",
                        Data = new { dllName = filename, typeName = type.FullName }
                    };
                }

                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return new JsonResult(
                    new ApiResultData<string>() { Success = false, Message = $"{ex.Message}" }
                );
            }
        }

        /// <summary>
        /// 获取所有分组
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllGroup")]
        public async Task<IActionResult> GetAllGroup()
        {
            List<JobInfoEntity> jobInfos = await _SchedulerCenter.GetAllJobAsync();
            var groupNames = _SchedulerCenter.GetJobGroupNames().Result;
            List<SelectListItem> groupNameList = new List<SelectListItem>();
            foreach (var group in groupNames)
            {
                groupNameList.Add(new SelectListItem() { Value = group, Text = group });
            }
            return await Task.FromResult(
                new JsonResult(
                    new ApiResultData<List<SelectListItem>>()
                    {
                        Message = "获取job分组",
                        Data = groupNameList,
                        Success = true,
                    }
                )
            );
        }

        /// <summary>
        /// 添加一个任务
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddJob")]
        public async Task<IActionResult> AddJob(ScheduleEntity entity)
        {
            ApiResult result = await _SchedulerCenter.AddScheduleJobAsync(entity);
            return new JsonResult(
                new ApiResult() { Success = result.Success, Message = result.Message, }
            );
        }

        /// <summary>
        /// 暂停任务执行
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("StopJob/{name}/{group}")]
        public async Task<IActionResult> StopJob(string name, string group)
        {
            ApiResult ApiResult = await _SchedulerCenter.StopOrDeleleteScheduleJobAsync(
                group,
                name
            );
            return new JsonResult(
                new ApiResult() { Success = ApiResult.Success, Message = ApiResult.Message }
            );
        }

        /// <summary>
        /// 继续执行任务
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ResumeJob/{name}/{group}")]
        public async Task<IActionResult> ResumeJob(string name, string group)
        {
            ApiResult ApiResult = await _SchedulerCenter.ResumeJobAsync(group, name);
            return new JsonResult(
                new ApiResult() { Success = ApiResult.Success, Message = ApiResult.Message }
            );
        }

        /// <summary>
        /// 立即执行
        /// </summary>
        /// <param name="group"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("TriggerJob/{name}/{group}")]
        public async Task<IActionResult> TriggerJob(string group, string name)
        {
            if (await _SchedulerCenter.TriggerJobAsync(new JobKey(name, group)))
            {
                return new JsonResult(new ApiResult() { Success = true, Message = "执行成功" });
            }
            else
            {
                return new JsonResult(new ApiResult() { Success = false, Message = "执行失败" });
            }
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="group"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("RemoveJob/{name}/{group}")]
        public async Task<IActionResult> RemoveJob(string group, string name)
        {
            ApiResult ApiResult = await _SchedulerCenter.StopOrDeleleteScheduleJobAsync(
                group,
                name,
                true
            );
            return new JsonResult(
                new ApiResult() { Success = ApiResult.Success, Message = ApiResult.Message }
            );
        }
    }
}
